<?php

namespace app\keeper\controller;

use app\common\lib\Str;
use app\common\model\mysql\In;
use app\common\model\mysql\InProduct;
use app\common\model\mysql\Out;
use app\common\model\mysql\OutProduct;
use app\common\model\mysql\Product;
use app\common\model\mysql\Supplier as supplierModel;
use app\common\model\mysql\Supplierin;
use app\common\model\mysql\Warehouse;
use app\common\model\mysql\SupplierinProductIn;
use app\common\model\mysql\SupplierinProductOut;
use app\common\model\mysql\WarehouseSpaceProduct;
use think\facade\Db;

class Supplier extends AuthBase
{
    /**
     * 供应商列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function supplierList(){
        $supplierWhere = [
            ['company_id','=',$this->companyId],
            ['shop_id','=',$this->shopId],
            ['isdel','=','0']
        ];
        $supplierData = (new supplierModel())->getNormalSupplierList($supplierWhere,'id as supplier_id,tname,leader,phone,address');
        return show(config("status.success"),"供应商列表",$supplierData);
    }

    /**
     * 供应商入库
     * @return \think\response\Json
     */
    public function putInStorage(){
        $supplier_id = $this->request->param('supplier_id');
        $warehouse_id = $this->request->param('warehouse_id');
        $warehouse_space_id = $this->request->param('warehouse_space_id');
        if(empty($supplier_id)){
            return show(config("status.error"),"缺少参数代理商id");
        }
        if(empty($warehouse_id)){
            return show(config("status.error"),"缺少参数仓库id");
        }
        if(empty($warehouse_space_id)){
            return show(config("status.error"),"缺少参数仓位id");
        }
        $remark = $this->request->param('remark', '');
        //入库数据：product_id,count,typeenum
        $goodsData = $this->request->param('goodsData');
        if(empty($goodsData)){
            return show(config("status.error"),"缺少参数商品数据");
        }
        //出库数据：product_id,count,warehouse_id,warehouse_space_id
        $bucketData = $this->request->param('bucketData');
        try {
            Db::startTrans(); // 开始事务
            foreach($goodsData as $value){
                if(!array_key_exists('product_id', $value) ||
                    !array_key_exists('count', $value) ||
                    !array_key_exists('typeenum', $value)) {
                    return show(config("status.error"), "商品数据传输有误");
                }
            }
            if($bucketData){
                foreach($bucketData as $value) {
                    if(!array_key_exists('product_id', $value) ||
                        !array_key_exists('count', $value) ||
                        !array_key_exists('warehouse_id', $value) ||
                        !array_key_exists('warehouse_space_id', $value)) {
                        return show(config("status.error"), "商品出桶数据传输有误");
                    }
                    $productWhere = [['product_id','=',$value['product_id']]];
                    $productData = (new Product())->getProductFind($productWhere,'product_id,typeenum,price_unit,tcount,product_name');
                    if($productData['tcount']<$value['count']){
                        return show(config("status.error"), "商品名称为".$productData['product_name']."的商品，库存不足!请核实后在出厂");
                    }
                }
            }
            $supplierData = (new supplierModel())->getSupplierFind([['id','=',$supplier_id]],'id,tname,leader,phone,address');
            $supplierin['company_id'] = $this->companyId;
            $supplierin['shop_id'] = $this->shopId;
            $supplierin['order_sn'] = (new Str())->makeOrderNo($this->shopId,3);
            $supplierin['worker_id_add'] = $this->workerId;
            $supplierin['worker_name_add'] = $this->workerName;
            $supplierin['supplier_id'] = $supplier_id;
            $supplierin['supplier_name'] = $supplierData['tname'];
            $supplierin['remark'] = $remark;
            $supplierin['adddate'] = date("Y-m-d H:i:s",time());
            $supplierinRes = (new Supplierin())->addSupplierinData($supplierin);
            if(empty($supplierinRes)){
                return show(config("status.error"),"入库失败");
            }
            $inAddData['company_id'] = $this->companyId;
            $inAddData['shop_id'] = $this->shopId;
            $inAddData['supplier_id'] = $supplier_id;
            $inAddData['supplier_name'] = $supplierData['tname'];
            $inAddData['warehouse_id'] = $warehouse_id;
            $inAddData['order_sn'] = (new Str())->makeOrderNo($this->shopId,6);
            $inAddData['worker_id'] = $this->workerId;
            $inAddData['worker_name'] = $this->workerName;
            $inAddData['adddate'] = date("Y-m-d H:i:s",time());
            $inAddData['note'] = "";
            $inAddData['intypeenum'] = 1;
            $inAddData['modeltypeenum'] = 16;
            $inAddData['modelid'] = $supplierinRes;
            $inAddRes = (new In())->addInData($inAddData);
            if(empty($inAddRes)){
                return show(config("status.error"),"入库失败");
            }
            $total_amount = 0;
            foreach ($goodsData as $key=>$value){
                $productData = (new Product())->getProductFind([['product_id','=',$value['product_id']]],'price_unit,tcount,product_name');
                $inproductData[$key]['in_id'] = $inAddRes;
                $inproductData[$key]['warehouse_id'] = $warehouse_id;
                $inproductData[$key]['warehouse_space_id'] = $warehouse_space_id;
                $inproductData[$key]['product_id'] = $value['product_id'];
                $inproductData[$key]['tcount'] = $value['count'];
                $inproductData[$key]['price_unit'] = $productData['price_unit'];
                $inproductData[$key]['producttypeenum'] = $value['typeenum'];
                $inproductData[$key]['count_before'] = $productData['tcount'];
                $inproductData[$key]['count_after'] = $productData['tcount']+$value['count'];
                $inproductData[$key]['adddate'] = date("Y-m-d H:i:s",time());
                $total_amount += $productData['price_unit']*$value['count'];
                (new Product())->saveInProductField([['product_id','=',$value['product_id']]],'tcount',$value['count']);
                $wSPWhere = [
                    ['a.warehouse_id','=',$warehouse_id],
                    ['a.warehouse_space_id','=',$warehouse_space_id],
                    ['a.product_id','=',$value['product_id']],
                    ['a.isdel','=','0']
                ];
                $warehouseSpaceProductData = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductFind($wSPWhere,'warehouse_space_product_id,tcount');
                if($warehouseSpaceProductData){
                    (new WarehouseSpaceProduct())->saveInWarehouseSpaceProductField([['warehouse_space_product_id','=',$warehouseSpaceProductData['warehouse_space_product_id']]],'tcount',$value['count']);
                }else{
                    $space['warehouse_id'] = $warehouse_id;
                    $space['warehouse_space_id'] = $warehouse_space_id;
                    $space['product_id'] = $value['product_id'];
                    $space['tcount'] = $value['count'];
                    $space['company_id'] = $this->companyId;
                    $space['shop_id'] = $this->shopId;
                    (new WarehouseSpaceProduct())->addWarehouseSpaceProductData($space);
                }
                //进货单入库产品
                $productin[$key]['supplierin_id'] = $supplierinRes;
                $productin[$key]['product_id'] = $value['product_id'];
                $productin[$key]['tcount'] = $value['count'];
                $productin[$key]['unitprice'] = $productData['price_unit'];
                $productin[$key]['producttypeenum'] = $value['typeenum'];
                $productin[$key]['product_name'] = $productData['product_name'];
                $productin[$key]['supplier_id'] = $supplier_id;
                $productin[$key]['supplier_name'] = $supplierData['tname'];
            }
            (new SupplierinProductIn())->addAllSupplierinProductIn($productin);
            (new InProduct())->addAllInProduct($inproductData);
            $inSaveData['total_amount'] = $total_amount;
            (new In())->saveInData($inAddRes,$inSaveData);
            if($bucketData){
                //添加出库单
                $outAddData['company_id'] = $this->companyId;
                $outAddData['shop_id'] = $this->shopId;
                $outAddData['order_sn'] = (new Str())->makeOrderNo($this->shopId,7);
                $outAddData['worker_id'] = $this->workerId;
                $outAddData['worker_name'] = $this->workerName;
                $outAddData['adddate'] = date("Y-m-d H:i:s",time());
                $outAddData['note'] = "";
                $outAddData['outtypeenum'] = 1;
                $outAddData['modeltypeenum'] = 16;
                $outAddData['modelid'] = $supplierinRes;
                $outRes = (new Out())->addOutData($outAddData);
                if(empty($outRes)){
                    return show(config("status.error"),"出库失败");
                }
                foreach ($bucketData as $k => $v) {
                    $productData = (new Product())->getProductFind([['product_id','=',$v['product_id']]],'product_id,typeenum,product_name,tcount,price_unit');
                    $outGoods[$k]['out_id'] = $outRes;
                    $outGoods[$k]['warehouse_id'] = $v['warehouse_id'];
                    $outGoods[$k]['warehouse_space_id'] = $v['warehouse_space_id'];
                    $outGoods[$k]['product_id'] = $v['product_id'];
                    $outGoods[$k]['tcount'] = $v['count'];
                    $outGoods[$k]['price_unit'] = $productData['price_unit'];
                    $outGoods[$k]['producttypeenum'] = $productData['typeenum'];
                    $outGoods[$k]['count_before'] = $productData['tcount'];
                    $outGoods[$k]['count_after'] = $productData['tcount']-$v['count'];
                    $outGoods[$k]['adddate'] = date("Y-m-d H:i:s",time());
                    $wSPWhere = [
                        ['warehouse_id','=',$v['warehouse_id']],
                        ['warehouse_space_id','=',$v['warehouse_space_id']],
                        ['product_id','=',$productData['product_id']],
                        ['isdel','=','0']
                    ];
                    (new WarehouseSpaceProduct())->saveDecWarehouseSpaceProductField($wSPWhere,'tcount',$v['count']);
                    (new Product())->saveDecProductField([['product_id','=',$productData['product_id']]],'tcount',$v['count']);
                    //进货单出库产品
                    $GoodsOut[$k]['supplierin_id'] = $supplierinRes;
                    $GoodsOut[$k]['product_id'] = $productData['product_id'];
                    $GoodsOut[$k]['product_name'] = $productData['product_name'];
                    $GoodsOut[$k]['unitprice'] = $productData['price_unit'];
                    $GoodsOut[$k]['tcount'] = $v['count'];
                    $GoodsOut[$k]['producttypeenum'] = $productData['typeenum'];
                    $GoodsOut[$k]['supplier_id'] = $supplier_id;
                    $GoodsOut[$k]['supplier_name'] = $supplierData['tname'];
                }
                (new OutProduct())->addAllOutProduct($outGoods);
                (new SupplierinProductOut())->addAllSupplierinProductOut($GoodsOut);
            }
            // 提交事务
            Db::commit();
            return show(config("status.success"),"操作成功",['success'=>200]);
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            return show(config("status.error"),$e->getMessage());
        }
    }

    /**
     * 供应商入库历史
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function libraryHistory(){
        $page = $this->request->param('pageNum', 1);//当前页
        $limit = $this->request->param('pageSize', 10);//每页显示条数
        if(empty($page) || empty($limit)){
            return show(config("status.error"),"缺少分页参数");
        }
        $where = [
            ['company_id','=',$this->companyId],
            ['shop_id','=',$this->shopId],
            ['intypeenum','=',1],
            ['isdel','=','0']
        ];
        $historyList = (new In())->getNormalInList($where,$limit,$page,'id as in_id,supplier_id,adddate,total_amount,worker_name,worker_id,supplier_name');
        $historyList = $historyList['data'];
        foreach ($historyList as $key=>$value){
            $historyList[$key]['count'] = (new InProduct())->getNormalInProductSum([['in_id','=',$value['in_id']]],'tcount');
        }
        return show(config("status.success"),"供应商入库历史",$historyList);
    }

    /**
     * 供应商入库详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function putInDetails(){
        $in_id = $this->request->param('in_id');
        if(empty($in_id)){
            return show(config("status.error"),"缺少参数入库单id");
        }
        $pinData = (new In())->getInFind([['id','=',$in_id]],'id as in_id,note,adddate,total_amount,order_sn,supplier_name,warehouse_id,worker_name,modelid');
        $warehouseData = (new Warehouse())->getNormalWarehouseFind([['warehouse_id','=',$pinData['warehouse_id']]],'warehouse_name');
        $pinData['warehouse_name'] = $warehouseData['warehouse_name'];
        $field = "d.product_name,b.warehouse_name,c.warehouse_space_name,a.tcount,a.producttypeenum";
        $pinData['pinGoodsData'] = (new InProduct())->getNormalInProductList([['a.in_id','=',$in_id]],$field);
        $poutData = (new Out())->getOutFind([['modelid','=',$pinData['modelid']],['outtypeenum','=',1]],'id');
        if(empty($poutData)){
            $pinData['poutGoodsData'] = [];
        }else{
            $pinData['poutGoodsData'] = (new OutProduct())->getNormalOutProductList([['a.out_id','=',$poutData['id']]],$field);
        }
        return show(config("status.success"),"供应商入库详情",$pinData);
    }
}
